﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        const string FINAL = "FINAL";

        public Form1()
        {
            InitializeComponent();
            //webBrowser1.ScriptErrorsSuppressed = true;
            webBrowser1.Navigate("http://www.nfl.com/scores/2013/REG1");


            Timer t = new Timer();
            t.Interval = 60000;
            t.Tick += (x, y) =>
            {
                webBrowser1.Navigate("http://www.nfl.com/scores/2013/REG1");
            };
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            Week w =  DataBase.Weeks.GetCurrentWeek();
            var games = w.GetGames;
            var doc = new HtmlAgilityPack.HtmlDocument();
            var s = webBrowser1.Document.Body.InnerHtml.Replace("\n", "").Replace("\r", "");
            
            doc.LoadHtml(s);



            foreach (Game game in games)
            {
                if (game.GameState != Game.State.PostGame)
                {
                    bool changes = false;
                    string AwayScore;
                    string HomeScore;
                    string timeLeft;
                    var awayscorenode = doc.DocumentNode.SelectSingleNode(string.Format("//div [@class='team-data']/div [@class='team-info']/p/a [.='{0}']/../../../p [@class='total-score'] ", game.AwayTeam.TeamName));
                    var homescorenode = doc.DocumentNode.SelectSingleNode(string.Format("//div [@class='team-data']/div [@class='team-info']/p/a [.='{0}']/../../../p [@class='total-score'] ", game.HomeTeam.TeamName));
                    var timeleftnode = doc.DocumentNode.SelectSingleNode(string.Format("//div [@class='team-data']/div [@class='team-info']/p/a [.='{0}']/../../../../../../div[@class='game-center-area']/p/span [@class='time-left'] ", game.AwayTeam.TeamName));

                    if (timeleftnode != null && homescorenode != null && awayscorenode != null)
                    {
                        AwayScore = awayscorenode.InnerHtml;
                        HomeScore = homescorenode.InnerHtml;
                        timeLeft = timeleftnode.InnerHtml;


                        changes = scoreChanged(game, AwayScore, HomeScore, timeLeft);

                        if (changes)
                        {

                            DataBase.Games.UpdateGame(game);

                            if (game.GameState == Game.State.PostGame)
                                Helper.ProjectWinner(game.GameWeek);
                        }
                    }
                }
            }
        }

        const int iEmptyScore = -1;
        private static bool scoreChanged(Game game, string AwayScore, string HomeScore, string timeLeft)
        {
            bool changes = false;

            int newAwayScore = GetScore(game.AwayScore, AwayScore);
            int newHomeScore = GetScore(game.HomeScore, HomeScore);
            if (game.AwayScore != newAwayScore || game.HomeScore != newHomeScore)
            {
                game.AwayScore = newAwayScore;
                game.HomeScore = newHomeScore;
                changes = true;
            }

            if (timeLeft.Contains("ET"))
            {
                if (game.GameState != Game.State.PreGame)
                {
                    game.GameState = Game.State.PreGame;
                    changes = true;
                }
            }
            else if (timeLeft == FINAL)
            {
                if (game.GameState != Game.State.PostGame)
                {
                    if (game.AwayScore > game.HomeScore)
                    {
                        game.WinningTeamID = game.AwayTeam.ID;
                        game.LosingTeamID = game.HomeTeam.ID;
                    }
                    else if (game.AwayScore < game.HomeScore)
                    {
                        game.WinningTeamID = game.HomeTeam.ID;
                        game.LosingTeamID = game.AwayTeam.ID;
                    }

                    changes = true;
                    game.GameState = Game.State.PostGame;

                }
            }
            else if (game.GameState != Game.State.InGame)
            {
                if (game.GameState != Game.State.InGame)
                {
                    game.GameState = Game.State.InGame;
                    changes = true;

                    //new ChatHub().InsertGameStart(string.Format("{0} @ {1} Has Started", game.AwayTeam.TeamName, game.HomeTeam.TeamName), (int)game.GameWeek.ID);


                }
            }

            return changes;
        }

        private static int GetScore(int currentScore, string NewScore)
        {
            if (NewScore == EmptyScore || NewScore.Contains("#"))
                return iEmptyScore;
            else
            {
                int score = int.Parse(NewScore);

                return score;
            }
        }

        const string EmptyScore = "--";


    }
}
